/**
 * 账单服务层
 * by:fanqunxing
 */
const accountDAO = require('../DAO/accountDAO.js');
const { getOpenid } = require('../dbCloud.js');
const utils = require('../lib/utils.js');

const ACCOUNT_MAP = {
  5: '网购',
  4: '转账',
  1: '餐饮',
  2: '购物',
  3: '交通',
  99: '其他'
};
/**
 * 求和总支出
 */
const queryTotalAccount = async (params) => {
  var total = 0;
  var currentMonthTotal = 0;
  var userId = getOpenid();
  var allAccounts = await accountDAO.queryAllAccounts(userId);
  allAccounts.data.forEach(item => {
    var accountVal = item.accountVal / 1 || 0;
    total += accountVal / 1;
    if (utils.isCurrentMonth(item.time)) {
      currentMonthTotal += accountVal / 1;
    }
  });
  return {
    currentMonthTotal: currentMonthTotal.toFixed(2),
    total: total.toFixed(2)
  };
};



/**
 * 分页查询记账信息
 */
const queryAccounts = async (params) => {
  // 用户
  var userId = getOpenid();
  // 每次查询数
  var limitNum = 30;
  var skipNum = params.skipNum;
  var result = await accountDAO.queryAccounts(userId, skipNum, limitNum);
  result.data.forEach(item => {
    item.accountTypeName = ACCOUNT_MAP[item.accountType];
  });
  return {
    list: result.data
  };
};

/**
 * 获取所有支出记录
 */
const queryAllAccounts = async () => {
  var userId = getOpenid();
  var result = await accountDAO.queryAllAccounts(userId);
  return result;
}

/**
 * 根据主键删除支出
 */
const deleteAccountById = async (params) => {
  var id = params.id;
  return accountDAO.deleteAccountById(id);
};


/**
 * 根据主键获取支出
 */
const queryAccountById = async (params) => {
  var id = params.id;
  var result = await accountDAO.queryAccountById(id);
  result.data.accountTypeName = ACCOUNT_MAP[result.data.accountType]
  return result;
}

/**
 * 获取各个类型总和
 */
const getAllTypeCount = async (params) => {
  var resultMap = {};
  var userId = getOpenid();
  var result = await accountDAO.queryAllAccounts(userId);
  result.data.forEach(item => {
    const accountVal = item.accountVal / 1 || 0;
    const accountType = item.accountType;
    if (!resultMap[accountType]) {
      resultMap[accountType] = 0;
    }
    resultMap[accountType] += accountVal / 1;
  });
  var list = [];
  for (let key in resultMap) {
    resultMap[key] = resultMap[key].toFixed(2);
    var item = {
      name: ACCOUNT_MAP[key] || '未知',
      value: resultMap[key]
    }
    list.push(item);
  }
  return list;
};

/**
 * 新增账单
 */
const addAccout = async (params) => {
  params._openid = getOpenid();
  return await accountDAO.addAccout(params);
}

module.exports = {
  queryAccounts,
  queryAllAccounts,
  queryAccountById,
  deleteAccountById,
  getAllTypeCount,
  addAccout,
  queryTotalAccount
};